package com.ruanhb.wsp.util;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**
 * Created by r on 2018-8-30
 */
//@Slf4j
public class XstreamUtil {

    /**
     * XML转对象
     *
     * @param clazz 对象类
     * @param xml   字符串
     * @param <T>   T
     * @return
     */
    public static <T> T parseFromXml(Class<T> clazz, String xml) {
        //创建解析XML对象
        XStream xStream = new XStream(new DomDriver());
        //处理注解
        xStream.processAnnotations(clazz);
        @SuppressWarnings("unchecked")
        //将XML字符串转为bean对象
                T t = (T) xStream.fromXML(xml);
        return t;
    }


    /**
     * 对象转xml
     *
     * @param obj 对象
     * @return
     */
    public static String toXml(Object obj) {
        String hv = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        XStream xStream = new XStream(new DomDriver());
        xStream.autodetectAnnotations(true);
        xStream.processAnnotations(obj.getClass());
        String xml = xStream.toXML(obj);
        //替换回车、另起一行
        xml = xml.replaceAll("\n", "").replaceAll("\r", "");
        return hv + xml;
    }


}
